#!/usr/bin/python3
#coding:utf-8
__author__ 'merci'
import pymysql
import xlwt

def write_excel(data):
    book = xlwt.Workbook(encoding='utf-8')
    sheet = book.add_sheet(u'苏老的数据')
    #表头
    rows = ['id', 'catid', 'title', 'posttime', 'nums']
    #写入表头
    try:
        for i in range(len(rows)):
            sheet.write(0, i , rows[i])
    except:
        print("写入表头失败！")
    #写入数据
    try:
        for p in range(len(data)):
            for k in range(len(data[p])):
                sheet.write(p+1, k, data[p][k])
    except:
        print("写入数据失败！")
        
    book.save('sulao.xls')

def get_con():
    conn = False
    try:
        conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='sulao', charset='utf8')
    except:
        print("Connect failed !")
        conn = False
    return conn

def get_data():
    cursor = get_con().cursor()
    sql = """SELECT log_ID,log_CateID,log_Title,log_PostTime,log_ViewNums FROM zbp_post WHERE log_Status=0 ORDER BY log_ID ASC"""
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

if __name__ == "__main__":
    data = get_data()
    write_excel(data)